package com.per.mybootall.test;

import com.alibaba.fastjson.JSON;
import io.swagger.models.auth.In;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2022/3/31
 * Time: 18:03
 * Description:构造树形结构【map类型】
 */
public class test18 {
  public static void main(String[] args) {
    List<Map> initList=init();
    Map<Object,Map> tempMap=new HashMap();
    List<Map> tree=new ArrayList<>();
    for(Map item:initList){
      tempMap.put(item.get("id"),item);
      Integer pid=(Integer) item.get("pid");
      if(tempMap.containsKey(pid)){
        if(!tempMap.get(pid).containsKey("child")){
          tempMap.get(pid).put("child",new ArrayList());
        }
       List childList=(List) tempMap.get(pid).get("child");
        childList.add(item);
      }

      if(Integer.valueOf(item.get("pid").toString())==0){
        tree.add(item);
      }
    }

    System.out.println(JSON.toJSONString(tree));
  }
  public static List<Map> init(){
    return new ArrayList(){{
      add(new HashMap(){{put("id",1);put("pid",0);}});
      add(new HashMap(){{put("id",2);put("pid",0);}});
      add(new HashMap(){{put("id",3);put("pid",1);}});
      add(new HashMap(){{put("id",4);put("pid",2);}});
      add(new HashMap(){{put("id",5);put("pid",0);}});
      add(new HashMap(){{put("id",6);put("pid",4);}});
    }};
  }
}
